﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections.ObjectModel;
using DDU.DataModel;
using System.Windows.Input;
using DDU.Library;
using System.Windows;

namespace DDU.ViewModel
{
    public class SemesterViewModel : MainViewModel
    {
        public SemesterViewModel()
        {
            SelectedSemester = CurrentSemester;
        }

        private SemesterInfo selectedSemester;
        public SemesterInfo SelectedSemester
        {
            get { return selectedSemester; }
            set
            {
                selectedSemester = value;
                RaisePropertyChanged(() => SelectedSemester);
                RaisePropertyChanged(() => CoursesOfSemester);
                RaisePropertyChanged(() => DeleteCommand);
            }
        }

        public ObservableCollection<ScheduleInfo> CoursesOfSemester
        {
            get
            {
                if (SelectedSemester != null)
                {
                    return new ObservableCollection<ScheduleInfo>(Database.CollectionOfSchedules.Where(s => s.SemesterGuid == SelectedSemester.Guid).Distinct());
                }
                return null;
            }
        }

        private void Remove(SemesterInfo entity)
        {
            Database.CollectionOfSemesters.DeleteOnSubmit(entity);
            ScheduleInfo linkSchedule = Database.CollectionOfSchedules.FirstOrDefault(s => s.SemesterGuid == entity.Guid);
            if (linkSchedule != null)
            {
                Database.CollectionOfSchedules.DeleteOnSubmit(linkSchedule);
            }
            Submit();
            SelectedSemester = null;
            RaisePropertyChanged(() => SelectedSemester);
            RaisePropertyChanged(() => DeleteCommand);
            RaisePropertyChanged(() => ItemsOfSemesters);
        }

        public ICommand DeleteCommand
        {
            get
            {
                return new GenericCommand()
                {
                    CanExecuteCallback = delegate { return SelectedSemester != null; },
                    ExecuteCallback = delegate
                    {
                        if (MessageBox.Show("确定要删除吗？", "删除提醒", MessageBoxButton.OKCancel) == MessageBoxResult.OK)
                        {
                            Remove(SelectedSemester);
                        }
                    }
                };
            }
        }
    }
}
